/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/12/14
 */

import { queryAllUser } from 'services/user';
import { roleService } from 'services';
import { config, arrayToTree } from 'utils';
import { routerTool } from '../../utils';
import { message } from 'antd';

export default {
  namespace: 'organizationRole',

  state: {
    // 当前选择的部门
    firstLoaded: false,
    selectedRole: {},
    roles: [],
    currentRole: {},
    allUsers: [],
    selectedUsers: [],
    rightHasMore: true,
    leftHasMore: true,
  },

  reducers: {
    updateState (state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    addRole (state, { payload }) {
      const { role } = payload;
      state.roles.push(role);

      return {
        ...state,
      };
    },

    doFirstLoad (state) {
      return {
        ...state,
        ...{
          firstLoaded: true,
        },
      };
    },

    changeCurrentRole (state, { payload: { role } }) {
      if ((state.currentRole || { ID: null }).ID !== role.ID) {
        return {
          ...state,
          ...{
            currentRole: role, 
          },
        };
      }
      return {
        ...state,
      };
    },
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      return history.listen(location => {
        if (location.pathname === routerTool.getPathByName("OrganizationDepartment")) {
          dispatch({ type: 'watchCurrentRoleUpdate' });
          dispatch({ type: 'loadRoles' })
            .then(() => {
              dispatch({ type: 'firstLoad' });
            })
            .then(() => {
              dispatch({
                type: 'loadAllUsers',
                payload: {
                  page: config.DefaultPager.page,
                  limit: config.DefaultPager.pageSize,
                },
              });
              dispatch({
                type: 'loadSelectedUsers',
                payload: {
                  page: config.DefaultPager.page,
                  limit: config.DefaultPager.pageSize,
                },
              });
            })
            .then(() => {
              dispatch({
                type: 'doFirstLoad',
              });
            });
        }
      });
    },
  },

  effects: {

    *firstLoad (_, { put, select }) {
      const { firstLoaded } = yield select(_ => _.organizationRole);
      // console.log(firstLoaded, '=== 首次加载状态');
      if (firstLoaded) {
        yield put({
          type: 'updateState',
          payload: {
            allUsers: [],
            selectedUsers: [],
          },
        });
      }
    },

    // 加载所有部门
    *loadRoles (_, { call, put, select }) {
      // 获取当前组织
      // const { organization } = yield select(_ => _.user);
      const { success, results } = yield call(roleService.getAllCanUseRoles);

      if (success) {
        const { Roles } = results;
        const deptTree = arrayToTree(Roles, 'ID', 'GroupID', 'children').sort((a, b) => {
          let al = a.children ? a.children.length : 0;
          let bl = b.children ? b.children.length : 0;

          return al < bl;
        });

        // 更新部门
        yield put({
          type: 'updateState',
          payload: {
            roles: Roles,
            currentRole: ((deptTree[0] || {}).children || [])[0],
          },
        });
        // const { currentDept } = yield select(_ => _.organizationDepartment);
      }
    },

    // 创建角色
    *createRoleOrGroup ({ payload }, { call, put }) {
      const { postData } = payload;
      const { success, results, message: msg } = yield call(roleService.createRoleOrGroup, postData);
      if (success) {
        const { Record } = results;
        yield put({
          type: 'addRole',
          payload: {
            role: Record,
          },
        });

        message.success('创建成功');
      } else {
        message.error(msg);
      }
    },

    // 加载所有用户
    *loadAllUsers ({ payload }, { call, put, select }) {

      // const { allUsers } = yield select(_ => _.organizationDepartment);
      
      const { isLoad, page, limit, reload } = payload;
      let { allUsers } = yield select(_ => _.organizationRole);
      // console.log(allUsers, 'second allUsers');
      if (reload) {
        allUsers = [];  
      }
      let params = {
        page: config.DefaultPager.page,
        limit: config.DefaultPager.pageSize,
      };

      if (isLoad) {
        params = { page, limit };
      }
      
      const { success, results } = yield call(queryAllUser, params);
      if (success) {
        const { List, PageSize, Total } = results;

        // 如果没有超页
        if (page <= Math.ceil(Total / PageSize) || Total === 0) {
          
          allUsers = allUsers.concat(List);
          yield put({
            type: 'updateState',
            payload: {
              allUsers,
            },
          });
        } else {
          yield put({
            type: 'updateState',
            payload: {
              rightHasMore: false,
            },
          });
        }
      }
    },

    // 加载被选择的用户（当前部门内的用户）
    *loadSelectedUsers ({ payload }, { call, put, select }) {
      const { isLoad, page, limit, roleID, reload } = payload;
      // console.log(payload, 'HAHAHA');
      let { selectedUsers, currentRole } = yield select(_ => _.organizationRole);
      if (reload) {
        selectedUsers = [];
      }
      if (!currentRole) {
        yield put({
          type: 'updateState',
          payload: {
            selectedUsers: [],
          },
        });

        return;
      }
      let params = {
        page: config.DefaultPager.page,
        limit: config.DefaultPager.pageSize,
      };

      if (isLoad) {
        params = { page, limit };
      }
      if (roleID) {
        params.roleID = roleID;
      } else {
        params.roleID = currentRole.ID;
      }
      
      // console.log(currentDept, 'dept ===');
      const { success, results } = yield call(roleService.getUsersInRole, params);
      if (success) {
        const { List, PageSize, Total } = results;

        // 如果没有超页
        if (page <= Math.ceil(Total / PageSize) || Total === 0) {
          
          selectedUsers = selectedUsers.concat(List);
          
          yield put({
            type: 'updateState',
            payload: {
              selectedUsers,
            },
          });
        } else {
          yield put({
            type: 'updateState',
            payload: {
              leftHasMore: false,
            },
          });
        }
      }
    },

    // 将用户加到部门
    *addUserToRole ({ payload }, { call, put, select }) {
      const { users } = payload;
      
      const { currentRole, allUsers, selectedUsers } = yield select(_ => _.organizationRole);
  
      const { success } = yield call(roleService.addUsersToRole, {
        users,
        roleID: currentRole.ID,
      });
  
      if (success) {
        // 将操作的用户加入到被选择的列表
        const actionUsers = allUsers.filter(_ => users.includes(_.ID));
        yield put({
          type: 'updateState',
          payload: {
            selectedUsers: [
              ...selectedUsers,
              ...actionUsers,
            ],
          },
        });
        // 通知操作成功
        message.success('操作成功');
      } else {
        message.error('操作失败');
      }
    },
  
    // 将用户从部门移除
    *removeUserFromRole ({ payload }, { call, put, select }) {
      const { users } = payload;
      const { currentRole, selectedUsers } = yield select(_ => _.organizationRole);
      const { success } = yield call(roleService.removeUsersFromRole, {
        users,
        roleID: currentRole.ID,
      });
  
      if (success) {
        const changedSelectedUsers = selectedUsers.filter(_ => !users.includes(_.ID));
        yield put({
          type: 'updateState',
          payload: {
            selectedUsers: changedSelectedUsers,
          },
        });
        
        message.success('操作成功');
      } else {
        message.error('操作失败');
      }
    },

    // 部门变更监听器
    watchCurrentRoleUpdate: [function* ({ take, put }) {
      while (true) {
        const { payload: { role } } = yield take('changeCurrentRole');
        console.log('change --> ', role);
        yield put({
          type: 'loadAllUsers',
          payload: {
            page: config.DefaultPager.page,
            limit: config.DefaultPager.pageSize,
            reload: true,
          },
        });
        yield put({
          type: 'loadSelectedUsers',
          payload: {
            roleID: role.ID,
            page: config.DefaultPager.page,
            limit: config.DefaultPager.pageSize,
            reload: true,
          },
        });
      }
    }, { type: 'watcher' }],
  },

};

